package com.idc.common.util;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.springframework.util.ReflectionUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogUtil {

	private static Method printStackTraceMethod;
	private static Method printStackTraceArgsMethod;
	private static Method logErrorMethod;
	private static Method logInfoMethod;
	static {
		try {
			printStackTraceMethod = Throwable.class.getMethod("printStackTrace");
			printStackTraceArgsMethod = Throwable.class.getMethod("printStackTrace", PrintWriter.class);
			logInfoMethod = log.getClass().getMethod("info", String.class,Object[].class);
			logErrorMethod = log.getClass().getMethod("error", String.class,Object[].class);
			ReflectionUtils.makeAccessible(printStackTraceMethod);
			ReflectionUtils.makeAccessible(printStackTraceArgsMethod);
			ReflectionUtils.makeAccessible(logInfoMethod);
			ReflectionUtils.makeAccessible(logErrorMethod);
		} catch (NoSuchMethodException | SecurityException e) {
			throw new RuntimeException(e);
		}
	}

	public static void info(Logger log,String msg,Object...objects){
		try {
			logInfoMethod.invoke(log,new Object[]{msg,objects});
		} catch (IllegalAccessException |InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}

	public static void error(Logger log,String msg,Object...objects){
		try {
			logErrorMethod.invoke(log,new Object[]{msg,objects});
		} catch (IllegalAccessException |InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void printStackTrace(Throwable throwable) {
		try {
			printStackTraceMethod.invoke(throwable);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}

	public static void printStackTrace(Throwable throwable, PrintWriter printWriter) {
		try {
			printStackTraceArgsMethod.invoke(throwable, printWriter);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}

}
